<?php

namespace App\Http\Controllers\Guard\Rbac;

use App\Http\Controllers\Common\GuardController;
use App\Models\Constant\Constant;
use App\Models\Rbac\Role;
use App\Models\Rbac\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class RoleController extends GuardController {

    public function __construct() {
        $this->instance = new Role();
    }

    public function lst(Request $request) {
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',Constant::PAGE_SIZE);

        $records = $this->instance->getLst($request->input())->paginate($pageSize,$this->getCol,'page',$page);
        $mapPermission = (new Permission())->getLst([])->get();
        foreach ($records as $record) {
            $record->permission_names = $mapPermission->whereIn('id',explode(',',$record->permission_ids))->pluck('title')->implode(' - ');
        }
        return responseSuccess($records->items(),$records->total());
    }

    public function add(Request $request) {
        $id = $request->input('id',0);
        $name = $request->input('name');
        $beizhu = $request->input('beizhu');
        $selectPermissionIds = $request->input('selectPermissionIds');
        $this->validate($request,  [
            'selectPermissionIds'=>'required'
        ],[
        ],[
            'selectPermissionIds'=>'权限'
        ]);
        try{
            $permission_ids = implode(',', $selectPermissionIds);
            $info = compact('name','beizhu','permission_ids');
            $this->instance->updateOrCreate(['id'=>$id],$info);
            return responseSuccess();
        }catch (\Exception $exception){
            $msg = $exception->getFile().':'.$exception->getLine().':'.$exception->getMessage();
            return responseFail($msg);
        }
    }
}
